<template>
	<view>
		<view class="card" style="padding-bottom: 20rpx;">
			<view class="pcs">{{$z.$t("站点名称")}}：{{ Station.pcs }}</view>
			<view class="gtel">{{$z.$t("桩号")}}：{{ ChargeCar.gtel }}</view>

			<view class="u-flex tdbox">
				<u-button v-for="(item, key) in tds" :key="key" class="tditem" v-bind="item.attrs" :text="item.label"
					@click="itemtap(item)"></u-button>
			</view>
			<view class="dfjebox">
				{{$z.$t("电桩功率")}}：{{$z.xtypefn(ChargeCar.xtype)}}
				{{$z.defaultValue.getoption(ChargeCar.df2,"df2")}}
			</view>
			<view class="dfjebox">
				{{$z.$t("平台电压")}}：{{$z.defaultValue.getoption(ChargeCar.df1,"df1")}}
			</view>
		</view>

		<view class="card" style="padding: 20rpx 0 20rpx 0;">
			<view class="title u-flex">
				{{$z.$t("收费规则")}}：
			</view>
			<view class="dfjebox sfjebox" v-if="df && typeof df == 'object'">
				<view class="u-flex u-flex-between">
					<view class="">{{$z.$t("当前计费时段")}} {{ df.t1 }}-{{ df.t2 }}</view>
					<view @click="Stationxq(ChargeCar.gtel)" style="display: flex;">{{$z.$t("全部时段")}}<u-icon
							name="arrow-right"></u-icon></view>
				</view>
				<view class="u-flex" style="font-size: 32rpx;">
					{{$z.$t("收费规则")}}：
					<text class="dfje">{{ df.je3 }}</text>
					{{$z.$t("元/度")}}
				</view>
				<view class="u-flex u-flex-between jexq" style="color: #a9a9a9;">
					{{$z.$t("充电电费")}}{{df.je1}}{{$z.$t("元/度")}},{{$z.$t("平台服务费")}}{{df.je2 }}{{$z.$t("元/度")}}
				</view>
				<!-- 有地锁模式且金额设置大于0 的情况下展示 -->
				<view class="u-flex u-flex-between jexq" @click="goRoute(ChargeCar)"
					v-if="ChargeCar.type == 14 && ChargeCar.qbf > 0">
					{{$z.$t("超时占位费")}}{{occupancyFee}}
					<view style="display: flex;">详情<u-icon name="arrow-right"></u-icon></view>
				</view>
			</view>
			<view class="dfjebox sfjebox" v-else>
				<view class="u-flex u-flex-between">
					<view class="">{{$z.$t("当前计费时段")}}：00:00 -- 24:00</view>
					<view @click="Stationxq(ChargeCar.gtel)" style="display: flex;">{{$z.$t("全部时段")}}<u-icon
							name="arrow-right"></u-icon></view>
				</view>
				<view class="u-flex">
					{{$z.$t("当前收费规则")}}：
					<text class="dfje">{{ $z.$t(df) }}</text>
				</view>
			</view>
		</view>
		<u-popup :show="show" mode="center" @open="open" @close="close" :round="10">
			<view v-for="(order, index) in orders" :key="index" is-link @click="handleClick(order)">
				<view class="box">
					<view>
						<view class="order-title">订单{{index+1}}</view>

						<u-line direction="col" v-if="index !== orders.length-1" color="#0072f0" dashed></u-line>
					</view>
					<view class="order-item">
						<view class="order-time">开始时间: {{ order.sjc }}</view>
						<view class="order-footer">
							<view class='order-green'>设备ID:{{ order.gtel }}</view>
							<view class='order-orange'>通道:{{ order.td == 1 ? 'A枪' : 'B枪' }}</view>
						</view>
					</view>
				</view>
			</view>
		</u-popup>
	</view>

</template>

<script>
	import qs from "qs";
	export default {
		name: "cardtd",
		props: {
			ChargeCar: {
				type: Object,
				default: () => {},
			},
			ChargeUser: {
				type: Array,
				default: () => [],
			},
			Station: {
				type: Object,
				default: () => {},
			},
			value: {
				type: [String, Number],
				default: "0",
			},
			cddxtype: {
				type: Boolean,
				default: false,
			},
		},

		data() {
			return {
				orders: [],
				show: false
			};
		},
		asyncComputed: {
			async df() {
				if (this.cddxtype) {
					return `${this.$z.$t("车位费")}${this.ChargeCar.qbf / 100}${this.$z.$t("元")}/${this.ChargeCar.dfsj}${this.$z.$t("分钟")}`;
				}

				let ChargeCar = this.ChargeCar;
				if (!ChargeCar.gtel) {
					return "0";
				}

				if (ChargeCar.type == "1") {
					return `${Number(ChargeCar.df).div(100)} ${this.$z.$t("元/度")}`;
				}
				let dfarr1 = [
					[{
							label: this.$z.$t("尖峰"),
							value: "jdf",
						},
						{
							label: this.$z.$t("尖峰服务费"),
							value: "jfff",
						},
						["jsjsh", "jsjsm", "jsjeh", "jsjem"],
					],
					[{
							label: this.$z.$t("高峰"),
							value: "fdf",
						},
						{
							label: this.$z.$t("高峰服务费"),
							value: "ffff",
						},
						["fsjsh", "fsjsm", "fsjeh", "fsjem"],
					],
					[{
							label: this.$z.$t("平峰"),
							value: "pdf",
						},
						{
							label: this.$z.$t("平峰服务费"),
							value: "pfff",
						},
						["psjsh", "psjsm", "psjeh", "psjem"],
					],
					[{
							label: this.$z.$t("谷峰"),
							value: "gdf",
						},
						{
							label: this.$z.$t("谷峰服务费"),
							value: "gfff",
						},
						["gsjsh", "gsjsm", "gsjeh", "gsjem"],
					],
				];
				let times = [];
				dfarr1.forEach((e) => {
					let je1 = ChargeCar[e[0].value] / 100;
					let je2 = ChargeCar[e[1].value] / 100;
					let je3 = Number(ChargeCar[e[0].value])
						.add(Number(ChargeCar[e[1].value]))
						.div(100);

					let dsstr = "";
					for (let i = 1; i <= 5; i++) {
						let t1 = ChargeCar[`${e[2][0]}${i}`];
						let t2 = ChargeCar[`${e[2][1]}${i}`];
						let t3 = ChargeCar[`${e[2][2]}${i}`];
						let t4 = ChargeCar[`${e[2][3]}${i}`];
						if (!t1) {
							t1 = "0";
						}
						if (!t2) {
							t2 = "0";
						}
						if (!t3) {
							t3 = "0";
						}
						if (!t4) {
							t4 = "0";
						}
						t1 = t1 < 10 ? "0" + t1 : t1;
						t2 = t2 < 10 ? "0" + t2 : t2;
						t3 = t3 < 10 ? "0" + t3 : t3;
						t4 = t4 < 10 ? "0" + t4 : t4;

						if (!(t1 == 0 && t2 == 0 && t3 == 0 && t4 == 0)) {
							dsstr = t1 + ":" + t2 + "--" + t3 + ":" + t4;
							times.push([
								...e,
								{
									t1: `${t1}:${t2}`,
									t2: `${t3}:${t4}`,
									je1,
									je2,
									je3,
								},
							]);
						}
					}
				});
				// this.fys = times;
				let dqt = this.$z.timefn.gettime(0, new Date(), `hh:MM`);
				let dqtimes = times.findIndex((e) => {
					let h = dqt.split(":")[0];
					let M = dqt.split(":")[1];
					let h1 = e[3].t1.split(":")[0];
					let M1 = e[3].t1.split(":")[1];
					let h2 = e[3].t2.split(":")[0];
					let M2 = e[3].t2.split(":")[1];
					// 转数字
					h = Number(h);
					M = Number(M);
					h1 = Number(h1);
					M1 = Number(M1);
					h2 = Number(h2);
					M2 = Number(M2);
					return (
						(h1 < h && h < h2) || (h1 == h && M1 <= M) || (h2 == h && M2 >= M)
					);
				});

				if (dqtimes == "-1") {
					return "0";
				}
				return times[dqtimes][3];
			},
		},
		computed: {
			occupancyFee() {
				let res = this.$z.$t("{1}元/{2}分，前{3}分钟免费");
				res = res.replace(/\{1\}/g, this.ChargeCar.qbf / 100);
				res = res.replace(/\{2\}/g, this.ChargeCar.dfsj);
				res = res.replace(/\{3\}/g, this.ChargeCar.jebd);
				return res;

			},
			watchdata() {
				return [this.ChargeUser, this.tds]
			},
			tds() {
				let r = [];
				// 设备路数

				let gls = this.ChargeCar.gls || "0";
				let abc = [
					"A",
					"B",
					"C",
					"D",
					"E",
					"F",
					"G",
					"H",
					"I",
					"J",
					"K",
					"L",
					"M",
					"N",
					"O",
					"P",
					"Q",
					"R",
					"S",
					"T",
					"U",
					"V",
					"W",
					"X",
				];
				for (let i = 1; i <= gls; i++) {
					let tdzts = [{
							type: "primary",
							plain: true,
						},
						{
							type: "error",
							plain: true,
						},
						{
							type: "info",
							plain: true,
							disabled: true,
						},
					];
					// :disabled="true"
					let tdzt = this.ChargeCar[`gcdl${Number(i) }`];

					if (Number(this.ChargeCar[`gcdl${i}`]) >= 3) {
						tdzt = 0;
					}
					if (this.ChargeCar[`glzt${i}`] != "0" || !tdzt) {
						tdzt = this.ChargeCar["glzt" + i];

					}
					if (!tdzt && tdzt != 0) {

						tdzt = "2";
					}

					if (this.ChargeCar.gls == 4) {
						tdzt = this.ChargeCar["glzt" + i];
					}
					// tdzt = "1";
					// if (this.ChargeCar.type == "14") {
					// 	let p = this.$u.$parent.call(this, "Chargecar");

					// 	if (p.zftext != this.$z.$t("打开地锁") && i == this.value) {
					// 		tdzt = "0";
					// 	}
					// }
					if (this.ChargeCar.gtype == 2) {
						tdzt = this.ChargeCar["glzt" + i];
					}

					let p = {
						label: `${this.$z.$t("充电")}${abc[i - 1]}${this.$z.$t("号枪")}`,
						td: String(i),
						attrs: tdzts[tdzt],
					};
					if (i == this.value) {
						p.attrs.plain = false;
					}
					r.push(p);
				}
				return r;
			},
		},
		watch: {
			watchdata: {
				handler() {
					if (!this.tds.length) return
					let p = this.$u.$parent.call(this, "Chargecar");

					let dqChargeUser = this.ChargeUser.find(e => {
						return e.gtel == this.ChargeCar.gtel && e.b_end == 0 && e.td == p.query.td
					})
					const hasValueZero = this.ChargeUser.some(item => item.b_end == 0);



					// alert(JSON.stringify(this.tds));
					let oktd = this.tds.find((e) => {
						return e.attrs.type == "primary";
					});
					// 情况一： 单设备单通道的场景
					// 在该场景中， a用户扫描设备A的二维码后将启动充电功能。 若a用户在后续再次扫描同一二维码， 则直接跳转到订单充电页， 
					// 扫描其它二维码则沿用系统目前的判定（ 若存在又重复扫已经自己启动订单的二维码， 则跳转到订单充电页）； 
					// 若b用户扫该设备二维码则系统将弹出提示窗口， 告知用户“ 当前该通道已被占用， 请选择其它充电桩”。
					// !oktd &&
					const allPrimary = this.tds.every(e => e.attrs.type === 'primary');

					if (dqChargeUser) {

						uni.redirectTo({
							url: `/pages/ChargeUser/ChargeUser`
						});
					} else if (!oktd) {

						p.loading = true;
						this.$emit("input", "");
						p.$refs.zmodal.init({
							content: this.$z.$t("当前该通道已被占用， 请选择其它充电桩！！"),

							confirm: () => {
								this.$z.sys();
							},
						});
					} else if (hasValueZero && p.query.td == 0) {

						// let arr = [{
						// 		sjc: '2024-02-02 12:03',
						// 		gtel: '12345678945',
						// 		td: '1',
						// 		b_end: 0
						// 	},
						// 	{
						// 		sjc: '2024-02-02 12:03',
						// 		gtel: '12345678945',
						// 		td: '1',
						// 		b_end: 0
						// 	},
						// 	{
						// 		sjc: '2024-02-02 12:03',
						// 		gtel: '12345678945',
						// 		td: '2',
						// 		b_end: 1
						// 	},
						// ]
						const count = this.ChargeUser.filter(item => item.b_end == 0).length;
						this.orders = this.ChargeUser
						// let count = arr.filter(item => item.b_end == 0).length;
						// this.orders = arr

						// this.tds.length == 2 &&
						// const cancelText = count > 0 ?
						// 	this.$z.$t(`打开正在充电的订单 (${count})`) :
						// 	this.$z.$t(`打开正在充电的订单`);
						const cancelText = count > 0 ?
							this.$z.$t(`打开正在充电的订单 `) :
							this.$z.$t(`打开正在充电的订单`);
						p.$refs.zmodal.init({
							content: this.$z.$t("尊敬的用户，您好，系统检测到您当前有正在充电的订单，请选择本次扫码: "),
							showcancel: false,
							showconfirm: false,
							isShowCornerMark: count > 1 ? true : false,
							orderNum: count,
							title: this.$z.$t("温馨提示"),
							confirmText: this.$z.$t("开启新的充电订单"),
							cancelText: this.$z.$t(`打开正在充电的订单 `),
							type: "nbtn",
							confirm: async () => {
								await this.itemtap(oktd, true);
								this.$nextTick(() => {
									p.$refs.zmodal.close();
								});
							},
							cancel: () => {
								// uni.redirectTo({
								// 	url: `/pages/ChargeUser/ChargeUser`
								// });
								if (count > 1) {
									this.open()
								} else {
									uni.redirectTo({
										url: `/pages/ChargeUser/ChargeUser`
									});
								}

							}

						});
					} else if (p.query.td != "0") {

						// alert(JSON.stringify(p.query))
						let tds = this.tds.find((e) => {
							return e.td == p.query.td;
						});
						// alert(JSON.stringify(tds))
						if (!tds || tds.attrs.type != "primary") {

							p.$refs.zmodal.init({
								content: this.$z.$t("当前该通道已被占用， 请选择通道！！"),

								confirm: () => {
									this.$z.sys();
								},
							});
						}
					}
					// 情况二： 单设备双通道的场景
					// 在该场景中，设备具备通道A和B两个二维码。当用户首先扫描通道A的二维码进行充电启动后，若再次扫描通道A二维码，
					// 则系统将直接跳转至“订单充电中”的页面。如果用户扫描通道B的二维码，则将跳转至“启动充电”页面。此外，如果用户扫描充电桩的设备二维码，
					// 系统会弹出选择窗口，让用户选择是跳转至通道A正在充电的界面，还是跳转至通道B的启动充电页面。如果通道B尚未被其他用户占用，则跳转将成功；
					// 若已被占用，系统将弹出提示信息，告知用户“当前该通道已被占用，请选择其他设备”。
					// 情况三：切换设备的场景
					// 在该场景中，用户首次扫描某一设备二维码并成功启动充电后，若接下来扫描其他设备的二维码，系统将保持目前的逻辑不变。
					// 系统首先判断所扫描的通道是否被其他用户占用。如果该通道已被占用，则弹出相关提示；若未被占用，则跳转至“启动充电”页面。
					console.log(this.watchdata, "watchdata");
				},
				immediate: false
			},
			tds() {
				// if (
				// 	this.tds.length == 1 &&
				// 	this.value != this.tds[0].td &&
				// 	this.tds[0].attrs.type == "primary"
				// ) {
				// 	this.itemtap(this.tds[0]);
				// }

				// let oktd = this.tds.find((e) => {
				// 	return e.attrs.type == "primary";
				// });
				// if (!oktd) {
				// 	this.$emit("tderr");
				// }
				// console.log(oktd, "tds");
			},

		},
		onLoad() {

		},
		methods: {
			// 去占位费详情页
			goRoute(val) {
				uni.navigateTo({
					url: `/pages/occupancyFeeDetails/occupancyFeeDetails?obj=${qs.stringify(val)}`,
				});
			},
			Stationxq(val) {
				// console.log('val', val);
				// return
				uni.navigateTo({
					url: `/pages/ChargeCarSys/components/dfxq?id=${val}`,
				});
			},
			async init() {},
			open() {
				this.show = true

			},
			close() {
				this.show = false
				// console.log('close');
			},
			handleClick(order) {
				// 多订单跳转 
				uni.redirectTo({
					url: `/pages/ChargeUser/ChargeUser?gtel=${order.gtel}&td=${order.td}`
				});
				console.log('Clicked on order:', order);
			},
			itemtap(item) {

				// , qzgx = false
				// let p = this.$u.$parent.call(this, "Chargecar");
				// p.query.td != "0" && 
				// if (!qzgx) {
				// 	return
				// }
				if (this.ChargeCar.type == "14") {
					let p = this.$u.$parent.call(this, "Chargecar");
					this.$u.toast(this.$z.$t("您当前打开的地锁与选择的充电枪不一致"));
					// if (p.zftext != this.$z.$t("打开地锁")) {
					// 	this.$u.toast(this.$z.$t("您有订单已经开始充电，请结束当前订单后再充。"));
					// 	return;
					// }
					return
				}
				if (item.attrs.type != "primary") {
					this.$u.toast(this.$z.$t("该通道已被占用请选择其他通道"));
					return;
				}
				this.$emit("input", item.td);
			},
		},
	};
</script>

<style lang="scss">
	::v-deep .u-safe-area-inset-bottom {
		padding: 0 !important;
	}

	.box {
		padding: 40rpx;
		display: flex;
		// justify-content: space-between;
	}

	.order-list {
		padding: 32rpx;
	}

	.order-title {
		font-size: 42rpx;
		color: #1989fa;
		font-weight: bold;
		margin-right: 10rpx;
		margin-bottom: 10rpx;
	}



	.order-time {
		font-size: 36rpx;
	}

	.order-footer {
		display: flex;
		justify-content: space-between;
		margin-top: 10rpx;
	}

	.order-label {
		font-size: 36rpx;
		color: #333;
	}

	.order-green {
		font-size: 32rpx;
		color: #1f8800
	}

	.order-orange {
		font-size: 32rpx;
		color: #ff4600
	}

	.tdbox {
		flex-wrap: wrap;
		padding-left: 40rpx;
		padding-right: 40rpx;
		padding-top: 20rpx;
		// justify-content: space-between;
	}

	// 56 -44  +8 -18
	.dfjebox {
		padding-left: 40rpx;
		font-size: 28rpx;
		line-height: 44rpx;
		color: #636363;

		.sfgz {
			font-size: 28rpx;
			height: 54rpx;
			display: flex;
			align-items: center;
		}

		.jexq {
			color: #636363;
			font-size: 28rpx;
			// height: 50rpx;
			display: flex;
			align-items: center;
		}
	}

	.sfjebox {
		padding-left: 30rpx;
		padding-right: 30rpx;
		line-height: 56rpx;
	}

	.tditem {
		width: auto;
		height: 60rpx;
		margin: 0;
		margin-right: 70rpx;
		margin-bottom: 18rpx;
	}

	.card {
		margin: 30rpx;
		background: #fff;
		border-radius: 20rpx;
		padding: 26rpx 0;
		line-height: 1;

		&::before {
			content: "";
			display: table;
			clear: both;
		}

		.title {
			font-size: 34rpx;
			font-weight: bold;
			height: 54rpx;
			padding-left: 30rpx;
		}

		.pcs {
			font-size: 32rpx;
			color: #333;
			font-weight: bold;
			display: flex;
			align-items: center;
			// margin: 20rpx 0;
			padding-left: 44rpx;
			position: relative;
			height: 52rpx;

			&::before {
				content: "";
				width: 6rpx;
				height: 26rpx;
				border-radius: 4rpx;
				display: inline-block;
				background: #417be9;
				position: absolute;
				left: 30rpx;
				// margin-right: 12rpx;
			}
		}

		.gtel {
			font-size: 32rpx;
			color: #333;
			font-weight: bold;
			display: flex;
			align-items: center;
			// margin: 20rpx 0;
			padding-left: 44rpx;
			position: relative;
			height: 52rpx;
		}
	}
</style>